# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.http import JsonResponse
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from rest_framework.authtoken.models import Token

from accounts.models import Profile
from .models import State

import json


@csrf_exempt
def login(request):
    body = json.loads(request.body)

    hash = body.get('hash', '')
    href = body.get('href', '')
    action = body.get('action', 'signin')

    state = State(hash=hash, href=href, action=action)
    state.save()

    url = '{0}{1}?state={2}'.format(settings.BASE_HOST, reverse('third:wechat_qrcode'), state.code)

    return JsonResponse(dict(
        errcode=0,
        url=url
    ))


@csrf_exempt
def check(request):
    body = json.loads(request.body)
    hash = body.get('hash', '')

    state = State.objects.filter(hash=hash, is_valid=True).first()

    if not state:
        return JsonResponse(dict(
            errcode=-1,
            errmsg='invalid hash'
        ))

    t = Token.objects.get_or_create(user=state.user)

    return JsonResponse(dict(
        errcode=0,
        token=t[0].key,
        href=state.href
    ))


@csrf_exempt
def bind(request):
    body = json.loads(request.body)

    token = body.get('token', '')
    hash = body.get('hash', '')
    href = body.get('href', '')
    action = body.get('action', 'bind')

    t = Token.objects.filter(key=token).first()

    if not t:
        return JsonResponse(dict(
            errcode=-1,
            errmsg='invalid token'
        ))

    state = State(user=t.user, hash=hash, href=href, action=action)
    state.save()

    url = '{0}{1}?state={2}'.format(settings.BASE_HOST, reverse('third:wechat_qrcode'), state.code)

    return JsonResponse(dict(
        errcode=0,
        url=url
    ))
